package com.mtsmda.test.comanda.d;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;

public class Task19022015_1407 {
	public static final int TASK1 = 1;
	public static final int TASK2 = 2;
	public static final int TASK3 = 3;
	public static final int ABOUT = 4;
	public static final int HELP = 5;

	public static final String TASK1_FILENAME_PREFIX = "spiralArray_MTSMDA_Task1_";
	public static final String TASK2_FILENAME_PREFIX = "readArray_MTSMDA_Task3_";
	public static final String TASK3_FILENAME_PREFIX = "infoDiskFiles_MTSMDA_Task3_";

	public static final String TXT = ".txt";

	private JFrame frame;
	private JMenuBar jMenuBar;
	private JMenu jMenuTascs, jMenuAbout, jMenuHelp, jMenuExit;
	private JMenuItem jMenuItemTask1, jMenuItemTask2, jMenuItemTask3,
			jMenuItemAbout, jMenuItemHelp, jMenuItemExit;

	private JPanel jPanelTask1, jPanelTask2, jPanelTask3, jPanelAbout,
			jPanelHelp;
	private JLabel jLabelTask1SizeArray;
	private JSpinner jSpinnerTask1SizeArray;
	private JButton jButtonTask1Generate, jButtonTask2ChooseFile;
	private JFileChooser jFileChooserTask2OpenFile;
	private JComboBox<String> jComboBoxDisksTask3;
	private String[] availableDisksTask3;
	private File[] availableDisksPathTask3;

	// private StreamTask3 streamTask3;

	public Task19022015_1407() {
		this.frame = new JFrame("Tasks");
		this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.frame.setPreferredSize(new Dimension(500, 250));

		this.frame.setJMenuBar(createMainMenu());

		this.frame.pack();
		this.frame.setLocationRelativeTo(null);
		this.frame.setVisible(true);
	}

	private JPanel task1(boolean visible) {
		this.jPanelTask1 = new JPanel(new FlowLayout());
		this.jPanelTask1.setVisible(visible);

		this.jLabelTask1SizeArray = new JLabel("Size array");
		this.jLabelTask1SizeArray.setToolTipText("Array square");
		this.jPanelTask1.add(jLabelTask1SizeArray);

		this.jSpinnerTask1SizeArray = new JSpinner(new SpinnerNumberModel(5, 2,
				100, 1));
		this.jPanelTask1.add(jSpinnerTask1SizeArray);

		this.jButtonTask1Generate = new JButton("Generate");
		this.jButtonTask1Generate.setToolTipText("Generate spiral array");
		this.jPanelTask1.add(jButtonTask1Generate);
		this.jButtonTask1Generate.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int size = 5;
				if (jSpinnerTask1SizeArray.getValue().toString() != null) {
					try {
						size = Integer.parseInt(jSpinnerTask1SizeArray
								.getValue().toString());
					} catch (Exception ex) {
						size = 9;
					}
				}
				int ar[][] = new int[size][size];
				SpiralArray.fillArrayRandomValues(ar);
				StringBuilder showArray = SpiralArray.showArray(ar);
				showArray.append(SpiralArray.showArraySpiral(ar));
				File writeToFileInfo = DirectoryTree.writeToFile(
						showArray,
						TASK1_FILENAME_PREFIX
								+ DirectoryTree.getNormalDateKind(0, true,
										false) + TXT);
				JOptionPane.showMessageDialog(frame, "Path - "
						+ writeToFileInfo.getAbsolutePath(), "Created file",
						JOptionPane.INFORMATION_MESSAGE);
				int response = JOptionPane.showConfirmDialog(frame,
						"Run file?", "Runnig new file",
						JOptionPane.YES_NO_CANCEL_OPTION);
				switch (response) {
				case JOptionPane.YES_OPTION: {
					Runtime runtime = Runtime.getRuntime();
					try {
						runtime.exec("C:/Program Files (x86)/Notepad++/notepad++.exe "
								+ writeToFileInfo.getAbsolutePath());
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(frame,
								"You don't installed or not found notepad++!",
								"Information", JOptionPane.ERROR_MESSAGE);
						try {
							runtime.exec("notepad.exe "
									+ writeToFileInfo.getAbsolutePath());
						} catch (Exception e2) {
							JOptionPane.showMessageDialog(frame,
									"You don't installed notepad",
									"Information", JOptionPane.ERROR_MESSAGE);
						}
					}
				}
					break;
				case JOptionPane.NO_OPTION: {
					JOptionPane.showMessageDialog(frame,
							writeToFileInfo.getAbsolutePath(), "Path to file",
							JOptionPane.INFORMATION_MESSAGE);
				}
					break;
				}

			}
		});

		return jPanelTask1;
	}

	private JPanel task2(boolean visible) {
		this.jPanelTask2 = new JPanel(new FlowLayout());

		this.jButtonTask2ChooseFile = new JButton("Choose file");
		this.jButtonTask2ChooseFile.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				jFileChooserTask2OpenFile = new JFileChooser();
				int showOpenDialog = jFileChooserTask2OpenFile
						.showOpenDialog(frame);
				if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
					File selectedFile = jFileChooserTask2OpenFile
							.getSelectedFile();
					if (selectedFile != null && selectedFile.exists()
							&& selectedFile.getAbsolutePath().endsWith(TXT)) {
						System.out.println(selectedFile.getAbsolutePath());
						StringBuilder readFile = ReadArrayFromFile
								.readFile(selectedFile.getAbsolutePath());
						File writeToFileInfo = DirectoryTree.writeToFile(
								readFile,
								TASK2_FILENAME_PREFIX
										+ DirectoryTree.getNormalDateKind(0,
												true, false) + TXT);
						JOptionPane.showMessageDialog(frame, "Path - "
								+ writeToFileInfo.getAbsolutePath(),
								"Created file", JOptionPane.INFORMATION_MESSAGE);

						int response = JOptionPane.showConfirmDialog(frame,
								"Run file?", "Runnig new file",
								JOptionPane.YES_NO_CANCEL_OPTION);
						switch (response) {
						case JOptionPane.YES_OPTION: {
							Runtime runtime = Runtime.getRuntime();
							try {
								runtime.exec("C:/Program Files (x86)/Notepad++/notepad++.exe "
										+ writeToFileInfo.getAbsolutePath());
							} catch (Exception e1) {
								JOptionPane
										.showMessageDialog(
												frame,
												"You don't installed or not found notepad++!",
												"Information",
												JOptionPane.ERROR_MESSAGE);
								try {
									runtime.exec("notepad.exe "
											+ writeToFileInfo.getAbsolutePath());
								} catch (Exception e2) {
									JOptionPane.showMessageDialog(frame,
											"You don't installed notepad",
											"Information",
											JOptionPane.ERROR_MESSAGE);
								}
							}
						}
							break;
						case JOptionPane.NO_OPTION: {
							JOptionPane.showMessageDialog(frame,
									writeToFileInfo.getAbsolutePath(),
									"Path to file",
									JOptionPane.INFORMATION_MESSAGE);
						}
							break;
						}

					} else {
						JOptionPane.showMessageDialog(frame, "Only " + TXT
								+ " files", "File not text",
								JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});

		this.jPanelTask2.add(jButtonTask2ChooseFile);

		return jPanelTask2;
	}

	private JPanel task3(boolean visible) {
		this.jPanelTask3 = new JPanel(new FlowLayout());
		this.jPanelTask3.setPreferredSize(new Dimension(200, 50));

		getDisks();
		this.jPanelTask3.add(new JLabel("Choose please available disk"));
		this.jPanelTask3.add(jComboBoxDisksTask3);

		JButton jButton = new JButton("Generate file");
		this.jPanelTask3.add(jButton);
		jButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				StringBuilder builder = new StringBuilder("");
				File root = new File(jComboBoxDisksTask3.getSelectedItem()
						.toString());

				// streamTask3 = new StreamTask3(root, builder, frame);

				// File writeToFile = streamTask3.getOutputFile();
				DirectoryTree.getFileTree(root, builder);
				File writeToFile = DirectoryTree.writeToFile(builder,
						TASK3_FILENAME_PREFIX + TXT);
				JOptionPane.showMessageDialog(frame,
						"Path - " + writeToFile.getAbsolutePath(),
						"Created file", JOptionPane.INFORMATION_MESSAGE);

				int response = JOptionPane.showConfirmDialog(frame,
						"Run file?", "Runnig new file",
						JOptionPane.YES_NO_CANCEL_OPTION);
				switch (response) {
				case JOptionPane.YES_OPTION: {
					Runtime runtime = Runtime.getRuntime();
					try {
						runtime.exec("C:/Program Files (x86)/Notepad++/notepad++.exe "
								+ writeToFile.getAbsolutePath());
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(frame,
								"You don't installed or not found notepad++!",
								"Information", JOptionPane.ERROR_MESSAGE);
						try {
							runtime.exec("notepad.exe "
									+ writeToFile.getAbsolutePath());
						} catch (Exception e2) {
							JOptionPane.showMessageDialog(frame,
									"You don't installed notepad",
									"Information", JOptionPane.ERROR_MESSAGE);
						}
					}
				}
					break;
				case JOptionPane.NO_OPTION: {
					JOptionPane.showMessageDialog(frame,
							writeToFile.getAbsolutePath(), "Path to file",
							JOptionPane.INFORMATION_MESSAGE);
				}
					break;
				}

			}
		});

		/*
		 * JButton jButtonStop = new JButton("Stop");
		 * jButtonStop.addActionListener(new ActionListener() {
		 * 
		 * @Override public void actionPerformed(ActionEvent e) {
		 * streamTask3.setSuspendFlag(false); if (!streamTask3.isRunning()) {
		 * File writeToFile = streamTask3.getOutputFile();
		 * JOptionPane.showMessageDialog(frame, "Path - " +
		 * writeToFile.getAbsolutePath(), "Created file",
		 * JOptionPane.INFORMATION_MESSAGE);
		 * 
		 * int response = JOptionPane.showConfirmDialog(frame, "Run file?",
		 * "Runnig new file", JOptionPane.YES_NO_CANCEL_OPTION); switch
		 * (response) { case JOptionPane.YES_OPTION: { Runtime runtime =
		 * Runtime.getRuntime(); try {
		 * runtime.exec("C:/Program Files (x86)/Notepad++/notepad++.exe " +
		 * writeToFile.getAbsolutePath()); } catch (Exception e1) { JOptionPane
		 * .showMessageDialog( frame,
		 * "You don't installed or not found notepad++!", "Information",
		 * JOptionPane.ERROR_MESSAGE); try { runtime.exec("notepad.exe " +
		 * writeToFile.getAbsolutePath()); } catch (Exception e2) {
		 * JOptionPane.showMessageDialog(frame, "You don't installed notepad",
		 * "Information", JOptionPane.ERROR_MESSAGE); } } } break; case
		 * JOptionPane.NO_OPTION: { JOptionPane.showMessageDialog(frame,
		 * writeToFile.getAbsolutePath(), "Path to file",
		 * JOptionPane.INFORMATION_MESSAGE); } break; } } } });
		 * this.jPanelTask3.add(jButtonStop);
		 */

		return jPanelTask3;
	}

	private JPanel about(boolean visible) {
		this.jPanelAbout = new JPanel(new BorderLayout());

		this.jPanelAbout.add(new JLabel("MTSMDA - 20.02.2015"),
				BorderLayout.CENTER);
		this.jPanelAbout
				.add(new JLabel("For test program"), BorderLayout.NORTH);
		this.jPanelAbout.add(
				new JLabel("Current time - "
						+ DirectoryTree.getNormalDateKind(0, false, true)),
				BorderLayout.SOUTH);

		return jPanelAbout;
	}

	private JPanel help(boolean visible) {
		this.jPanelHelp = new JPanel(new FlowLayout());

		this.jPanelHelp.add(new JLabel("Excuse me! Under Construction!"));

		return jPanelHelp;
	}

	private JMenuBar createMainMenu() {
		this.jMenuBar = new JMenuBar();
		this.jMenuTascs = new JMenu("Tasks");
		this.jMenuBar.add(jMenuTascs);

		this.jMenuItemTask1 = new JMenuItem("Task 1");
		this.jMenuItemTask1.setToolTipText("Spiral Square Array");
		this.jMenuItemTask1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispetcher(TASK1);
			}
		});

		this.jMenuItemTask2 = new JMenuItem("Task 2");
		this.jMenuItemTask2.setToolTipText("Read Array From File");
		this.jMenuItemTask2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispetcher(TASK2);
			}
		});

		this.jMenuItemTask3 = new JMenuItem("Task 3");
		this.jMenuItemTask3.setToolTipText("Directory Tree");
		this.jMenuItemTask3.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispetcher(TASK3);
			}
		});

		this.jMenuTascs.add(jMenuItemTask1);
		this.jMenuTascs.add(jMenuItemTask2);
		this.jMenuTascs.add(jMenuItemTask3);

		this.jMenuAbout = new JMenu("About");
		this.jMenuBar.add(jMenuAbout);
		this.jMenuItemAbout = new JMenuItem("About");
		this.jMenuItemAbout.setToolTipText("About this program");
		this.jMenuItemAbout.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispetcher(ABOUT);
			}
		});
		this.jMenuAbout.add(jMenuItemAbout);

		this.jMenuHelp = new JMenu("Help");
		this.jMenuItemHelp = new JMenuItem("Help");
		this.jMenuItemHelp.setToolTipText("How to use");
		this.jMenuItemHelp.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispetcher(HELP);
			}
		});
		this.jMenuHelp.add(jMenuItemHelp);
		jMenuBar.add(jMenuHelp);

		this.jMenuExit = new JMenu("Exit");
		this.jMenuItemExit = new JMenuItem("Exit");
		this.jMenuItemExit.setToolTipText("Exit - Shutdown program");
		this.jMenuItemExit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				exit();
			}
		});

		this.jMenuExit.add(jMenuItemExit);
		jMenuBar.add(jMenuExit);

		return jMenuBar;
	}

	private void exit() {
		int response = JOptionPane.showConfirmDialog(frame,
				"Do you want remove temp files, which created this program?",
				"Clear System", JOptionPane.YES_NO_CANCEL_OPTION);
		switch (response) {
		case JOptionPane.YES_OPTION: {
			File file = new File(System.getProperty("user.home"));
			if (file.exists() && file.isDirectory()) {
				File[] listFiles = file.listFiles();
				List<File> files = new ArrayList<File>();
				for (File file2 : listFiles) {
					if ((file2.getName().startsWith(TASK1_FILENAME_PREFIX)
							|| file2.getName()
									.startsWith(TASK2_FILENAME_PREFIX) || file2
							.getName().startsWith(TASK3_FILENAME_PREFIX))
							&& file2.getName().endsWith(TXT)) {
						files.add(file2);
					}
				}

				for (File file2 : files) {
					int showConfirmDialog = JOptionPane.showConfirmDialog(
							frame,
							"Do you want remove this '"
									+ file2.getAbsolutePath() + "' temp file?",
							"Current temp file", JOptionPane.YES_NO_OPTION);
					if (showConfirmDialog == JOptionPane.YES_OPTION) {
						boolean delete = file2.delete();
						if (delete) {
							JOptionPane.showMessageDialog(frame,
									file2.getAbsolutePath()
											+ " successfully deleted!",
									"Delete temp file",
									JOptionPane.INFORMATION_MESSAGE);
						}
					}
				}
			}
		}
			break;
		case JOptionPane.NO_OPTION: {

		}
			break;
		}
		System.exit(0);
	}

	private void dispetcher(int show) {
		switch (show) {
		case ABOUT: {
			removeComponentsInFrame(this.jPanelHelp, this.jPanelTask1,
					this.jPanelTask2, this.jPanelTask3);
			this.frame.add(about(true));
			this.frame.pack();
		}
			break;
		case HELP: {
			removeComponentsInFrame(this.jPanelAbout, this.jPanelTask1,
					this.jPanelTask2, this.jPanelTask3);
			this.frame.add(help(true));
			this.frame.pack();
		}
			break;
		case TASK1: {
			removeComponentsInFrame(this.jPanelAbout, this.jPanelHelp,
					this.jPanelTask2, this.jPanelTask3);
			this.frame.add(task1(true));
			this.frame.pack();
		}
			break;
		case TASK2: {
			removeComponentsInFrame(this.jPanelAbout, this.jPanelHelp,
					this.jPanelTask1, this.jPanelTask3);
			this.frame.add(task2(true));
			this.frame.pack();
		}
			break;
		case TASK3: {
			removeComponentsInFrame(this.jPanelAbout, this.jPanelHelp,
					this.jPanelTask1, this.jPanelTask2);
			this.frame.add(task3(true));
			this.frame.pack();
		}
			break;

		}
	}

	private void removeComponentsInFrame(Component... components) {
		if (components.length > 0) {
			for (Component component : components) {
				if (component != null) {
					this.frame.remove(component);
				}
			}
		}
	}

	public void getDisks() {
		this.availableDisksPathTask3 = DirectoryTree.getAllLocalDisks();
		this.availableDisksTask3 = new String[this.availableDisksPathTask3.length];
		int indexString = 0;
		for (int i = 0; i < this.availableDisksPathTask3.length; i++) {
			if (this.availableDisksPathTask3[i].getAbsolutePath() != null) {
				this.availableDisksTask3[indexString] = this.availableDisksPathTask3[i]
						.getAbsolutePath();
				indexString++;
			}
		}
		this.jComboBoxDisksTask3 = new JComboBox<>(availableDisksTask3);

	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				new Task19022015_1407();
			}
		});
	}

}

/*
 * class StreamTask3 implements Runnable { private File root; private
 * StringBuilder builder; private boolean suspendFlag; private Thread thread;
 * private JFrame frame;
 * 
 * private File outputFile;
 * 
 * public StreamTask3(File root, StringBuilder builder, JFrame frame) {
 * setBuilder(builder); setRoot(root); thread = new Thread(this); suspendFlag =
 * false; thread.start(); }
 * 
 * public void run() { if (root != null && builder != null) {
 * DirectoryTree.getFileTree(root, builder); } synchronized (this) { while
 * (suspendFlag) { try { wait(); } catch (InterruptedException e) {
 * e.printStackTrace(); } } } setSuspendFlag(false); }
 * 
 * public synchronized void mySuspend() { suspendFlag = true; }
 * 
 * public synchronized void myResume() { suspendFlag = false; notify(); }
 * 
 * public void setRoot(File root) { this.root = root; }
 * 
 * public void setBuilder(StringBuilder builder) { this.builder = builder; }
 * 
 * public boolean isRunning() { return suspendFlag; }
 * 
 * public void setSuspendFlag(boolean running) { this.suspendFlag = running; if
 * (!this.suspendFlag) { outputFile = DirectoryTree.writeToFile(builder,
 * "info.txt"); this.thread.stop(); g(); } }
 * 
 * public File getOutputFile() { return outputFile; }
 * 
 * public Thread getThread() { return thread; }
 * 
 * public void g() {
 * 
 * File writeToFile = this.getOutputFile(); JOptionPane.showMessageDialog(frame,
 * "Path - " + writeToFile.getAbsolutePath(), "Created file",
 * JOptionPane.INFORMATION_MESSAGE);
 * 
 * int response = JOptionPane.showConfirmDialog(frame, "Run file?",
 * "Runnig new file", JOptionPane.YES_NO_CANCEL_OPTION); switch (response) {
 * case JOptionPane.YES_OPTION: { Runtime runtime = Runtime.getRuntime(); try {
 * runtime.exec("C:/Program Files (x86)/Notepad++/notepad++.exe " +
 * writeToFile.getAbsolutePath()); } catch (Exception e1) {
 * JOptionPane.showMessageDialog(frame,
 * "You don't installed or not found notepad++!", "Information",
 * JOptionPane.ERROR_MESSAGE); try { runtime.exec("notepad.exe " +
 * writeToFile.getAbsolutePath()); } catch (Exception e2) {
 * JOptionPane.showMessageDialog(frame, "You don't installed notepad",
 * "Information", JOptionPane.ERROR_MESSAGE); } } } break; case
 * JOptionPane.NO_OPTION: { JOptionPane.showMessageDialog(frame,
 * writeToFile.getAbsolutePath(), "Path to file",
 * JOptionPane.INFORMATION_MESSAGE); } break; }
 * 
 * }
 * 
 * public void setFrame(JFrame frame) { this.frame = frame; }
 * 
 * }
 */